package com.harassment.interception.interception.telephone;

import android.annotation.SuppressLint;
import android.os.IBinder;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;

import com.android.internal.telephony.ITelephony;
import com.harassment.interception.data.databases.HIDBUtil;
import com.harassment.interception.data.databases.HIDatabase;
import com.harassment.interception.data.databases.entities.BlackList;
import com.harassment.interception.data.databases.entities.InterceptedPhone;
import com.harassment.interception.data.databases.entities.WhiteList;
import com.harassment.interception.ui.fragments.interceptRecord.phoneFragment.PhoneListAdapter;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;

import io.reactivex.Completable;
import io.reactivex.CompletableEmitter;
import io.reactivex.CompletableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Action;
import io.reactivex.schedulers.Schedulers;

public class TelephoneInterception {
    private static final String TAG = "TelephoneInterception";
    private static PhoneListAdapter mPhoneListAdapter;
    private static LinearLayoutManager sLinearLayoutManager;

    public void telephoneInterception(String number) {
        //检查白名单
        if (whitePattern(number)) {
            return;
        }
        //检查黑名单
        if (blackPattern(number)) {
            stopCall(number);
        }
    }

    private boolean blackPattern(String number) {
        List<BlackList> blackLists = HIDBUtil.getBlackListDao().getBlackListForModel(HIDatabase.DARK_MODEL);
        String regex = null;
        boolean result = false;
        for (BlackList blackList : blackLists) {
            regex = "^" + blackList.getNumber() + "\\d*$";
            result = number.matches(regex);
            Log.d(TAG, "blackPattern: " + number + ".matches(" + regex + ")正则匹配结果：" + result);
            if (result) {
                return blackList.isPhone();
            }
        }
        BlackList blackList = HIDBUtil.getBlackListDao().getBlackListForNumber(number);
        if (blackList != null) {
            result = blackList.isPhone();
        }
        return result;
    }

    private boolean whitePattern(String number) {
        //得到模糊号码列表
        List<WhiteList> whiteLists = HIDBUtil.getWhiteListDao().getWhiteListForModel(HIDatabase.DARK_MODEL);
        String regex = null;
        boolean result = false;
        for (WhiteList whiteList : whiteLists) {
            regex = "^" + whiteList.getNumber() + "\\d*$";
            result = number.matches(regex);
            Log.d(TAG, "whitePattern: " + number + ".matches(" + regex + ")正则匹配结果：" + result);
            if (result) {
                return whiteList.isPhone();
            }
        }
        //是否是精确号码
        WhiteList whiteList = HIDBUtil.getWhiteListDao().getWhiteListForNumber(number);
        if (whiteList != null) {
            result = whiteList.isPhone();
        }
        return result;
    }

    private void stopCall(String number) {
        Log.d(TAG, "stopCall: 开始拦截电话");
        try {
            Method method = Class.forName("android.os.ServiceManager").getMethod("getService", String.class);
            IBinder binder = (IBinder) method.invoke(null, new Object[]{"phone"});
            ITelephony iTelephony = ITelephony.Stub.asInterface(binder);
            iTelephony.endCall();
            InterceptedPhone interceptedPhone = new InterceptedPhone();
            interceptedPhone.setNumber(number);
            interceptedPhone.setDateTime(new Date(System.currentTimeMillis()));
            //写入数据库
            HIDBUtil.getInterceptedPhoneDao().addInterceptedPhone(interceptedPhone);
            refreshList(interceptedPhone);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.d(TAG, "stopCall: 拦截成功");
    }

    @SuppressLint("CheckResult")
    private void refreshList(final InterceptedPhone interceptedPhone) {
        if (mPhoneListAdapter == null) {
            return;
        }
        if (sLinearLayoutManager == null) {
            return;
        }
        //刷新列表
        Completable.create(new CompletableOnSubscribe() {
            @Override
            public void subscribe(CompletableEmitter emitter) throws Exception {
                mPhoneListAdapter.getInterceptedPhones().add(0, interceptedPhone);
                mPhoneListAdapter.selectInit(mPhoneListAdapter.getInterceptedPhones().size(), false);
                emitter.onComplete();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action() {
                    @Override
                    public void run() throws Exception {
                        mPhoneListAdapter.notifyDataSetChanged();
                        sLinearLayoutManager.scrollToPosition(0);
                    }
                });
    }

    public static PhoneListAdapter getPhoneListAdapter() {
        return mPhoneListAdapter;
    }

    public static void setPhoneListAdapter(PhoneListAdapter phoneListAdapter) {
        mPhoneListAdapter = phoneListAdapter;
    }

    public static LinearLayoutManager getLinearLayoutManager() {
        return sLinearLayoutManager;
    }

    public static void setLinearLayoutManager(LinearLayoutManager linearLayoutManager) {
        sLinearLayoutManager = linearLayoutManager;
    }

}
